package com.wujunshen.designpattern.creational.factory.simplefactory.reflection;

import com.wujunshen.designpattern.creational.factory.IVehicle;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author frank woo(吴峻申) <br>
 *     email:<a href="mailto:frank_wjs@hotmail.com">frank_wjs@hotmail.com</a> <br>
 * @date 2021/8/10 16:55<br>
 */
public class SimpleFactory {
  private static final Map<Integer, Class<? extends IVehicle>> registerProductMap =
      new ConcurrentHashMap<>();

  public static void registerProduct(int brandCode, Class<? extends IVehicle> vehicleClazz) {
    registerProductMap.put(brandCode, vehicleClazz);
  }

  public static IVehicle createProduct(int brandCode)
      throws NoSuchMethodException, InvocationTargetException, InstantiationException,
          IllegalAccessException {
    Class<? extends IVehicle> productClazz = registerProductMap.get(brandCode);

    return productClazz.getDeclaredConstructor().newInstance();
  }
}
